package my.http;


import com.app.car.basis.Constants;
import com.app.car.bean.LoginBean;
import com.app.car.util.MyUtils;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import my.LogUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class MyHttpUtils {
    public final static String tag = "HTTP";
    public final static boolean DEBUG = Constants.DEBUG;

    private static final String BASE_URL = "";

    private static OkHttpClient okHttpClient;
    private static final int TIME_OUT = 30 * 1000;


    public static OkHttpClient getAsyncHttpClient() {

        if(okHttpClient == null){
            okHttpClient = new  OkHttpClient.Builder()
                    .connectTimeout(TIME_OUT, TimeUnit.MILLISECONDS)//设置连接超时时间
                    .readTimeout(TIME_OUT, TimeUnit.MILLISECONDS)//设置读取超时时间
                    .addInterceptor(new MyInterceptor())
//                    .addInterceptor(new TokenInterceptor())
                    .hostnameVerifier(new AllowAllHostnameVerifier())  //忽略证书  https://blog.csdn.net/yonghuming_jesse/article/details/104969120?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.no_search_link&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.no_search_link
                    .build();
        }
        return okHttpClient;
    }


//    public static void get(String url, MyParams myParams,
//                           MyHttpListener mListener, int what, Class<?> class1) {
//        Request.Builder buildRquest = new Request.Builder()
//                .url(getAbsoluteUrl(url))
//                .put(myParams.getRequestBodyJson())
//                .get();
//        AddHeaderToBuilder(buildRquest,myParams,true);
//        Request request = buildRquest.build();
//        getAsyncHttpClient().newCall(request).enqueue(new MyHttpResposeHandler(mListener, what, class1));
//    }

    public static void delete(String url, MyParams myParams,
                           MyHttpListener mListener, int what, Class<?> class1) {

        Request.Builder buildRquest = new Request.Builder()
                .url(myParams.getHttpUrlBody(getAbsoluteUrl(url)).build())
                .delete();
        AddHeaderToBuilder(buildRquest,myParams,false);
        Request request = buildRquest.build();
        getAsyncHttpClient().newCall(request).enqueue(new MyHttpResposeHandler(mListener, what, class1));
    }

    public static void get(String url, MyParams myParams,
                           MyHttpListener mListener, int what, Class<?> class1) {

        Request.Builder buildRquest = new Request.Builder()
                .url(myParams.getHttpUrlBody(getAbsoluteUrl(url)).build());
        AddHeaderToBuilder(buildRquest);
        Request request = buildRquest.build();
        getAsyncHttpClient().newCall(request).enqueue(new MyHttpResposeHandler(mListener, what, class1));
    }
    


    public static void getExcute(String url, MyParams myParams,
                                 MyHttpListener mListener, int what, Class<?> class1) {
        Request.Builder buildRquest = new Request.Builder()
                .url(myParams.getHttpUrlBody(getAbsoluteUrl(url)).build());
        AddHeaderToBuilder(buildRquest,myParams,true);
        Request request = buildRquest.build();
        try {
//            Response response = getAsyncHttpClient().newCall(request).execute();
            OkHttpClient  okHttpClient = new  OkHttpClient.Builder().callTimeout(TIME_OUT, TimeUnit.MILLISECONDS).readTimeout(TIME_OUT,TimeUnit.MILLISECONDS).addInterceptor(new MyInterceptor()).build();
            Response response =   okHttpClient.newCall(request).execute();
            MyHttpResposeHandlerForSync myhandler = new MyHttpResposeHandlerForSync(mListener,0,class1);
            myhandler.onResponse(null,response);
        } catch (IOException e) {
            e.printStackTrace();
            mListener.onFailure(0,null);
        }
    }


    public static void post(String url, MyParams myParams,
                            MyHttpListener mListener, int what, Class<?> class1) {
        Request.Builder buildRquest = new Request.Builder()
                .url(getAbsoluteUrl(url))
                .post(myParams.getRequestBodyJson());
        AddHeaderToBuilder(buildRquest,myParams,false);
        Request request = buildRquest.build();
        getAsyncHttpClient().newCall(request).enqueue(new MyHttpResposeHandler(mListener, what, class1));
    }

    public static void postJson(String url, MyParams myParams,
                            MyHttpListener mListener, int what, Class<?> class1) {
        Request.Builder buildRquest = new Request.Builder()
                .url(getAbsoluteUrl(url))
                .post(myParams.getJson());
        AddHeaderToBuilder(buildRquest,myParams,false);
        Request request = buildRquest.build();
        getAsyncHttpClient().newCall(request).enqueue(new MyHttpResposeHandler(mListener, what, class1));
    }

    public static void post(String url, MyParams myParams,
                            MyHttpListener mListener, int what, Class<?> class1,int connectpasstime) {
        Request.Builder buildRquest = new Request.Builder()
                .url(getAbsoluteUrl(url))
                .post(myParams.getRequestBodyJson());
        AddHeaderToBuilder(buildRquest,myParams,false);
        Request request = buildRquest.build();
        OkHttpClient okHttpClient = new  OkHttpClient.Builder()
                .connectTimeout(connectpasstime*1000, TimeUnit.MILLISECONDS)//设置连接超时时间
                .readTimeout(connectpasstime*1000, TimeUnit.MILLISECONDS)//设置读取超时时间
                .addInterceptor(new MyInterceptor())
                .addInterceptor(new TokenInterceptor())
                .build();

        okHttpClient.newCall(request).enqueue(new MyHttpResposeHandler(mListener, what, class1));
    }

    public static void post(String url, MyParams myParams,
                            Callback callback) {
        Request.Builder buildRquest = new Request.Builder()
                .url(getAbsoluteUrl(url))
                .post(myParams.getRequestBodyJson());
        AddHeaderToBuilder(buildRquest,myParams,false);
        Request request = buildRquest.build();
        getAsyncHttpClient().newCall(request).enqueue(callback);
    }

    public static void postFile(String url, MyParams myParams,
                                MyHttpListener mListener, Class<?> class1) {
        Request.Builder buildRquest = new Request.Builder()
                .url(getAbsoluteUrl(url))
                .post(myParams.getRequestBodyWithFile());
        AddHeaderToBuilder(buildRquest,myParams,false);
        Request request = buildRquest.build();
            getAsyncHttpClient().newCall(request).enqueue(new MyHttpResposeHandler(mListener, 0, class1));

    }

    public static void postExcute(String url, MyParams myParams,
                            MyHttpListener mListener, int what, Class<?> class1) {
        Request.Builder buildRquest = new Request.Builder()
                .url(getAbsoluteUrl(url))
                .post(myParams.getRequestBodyJson());
        AddHeaderToBuilder(buildRquest,myParams,false);
        Request request = buildRquest.build();
        try {
//            Response response = getAsyncHttpClient().newCall(request).execute();
            OkHttpClient  okHttpClient = new  OkHttpClient.Builder().callTimeout(TIME_OUT, TimeUnit.MILLISECONDS).readTimeout(TIME_OUT,TimeUnit.MILLISECONDS).addInterceptor(new MyInterceptor()).build();
            Response response =   okHttpClient.newCall(request).execute();
            MyHttpResposeHandlerForSync myhandler = new MyHttpResposeHandlerForSync(mListener,0,class1);
            myhandler.onResponse(null,response);
        } catch (IOException e) {
            e.printStackTrace();
            mListener.onFailure(0,null);
        }
    }

    public static void postFileExcute(String url, MyParams myParams,
                                      MyHttpListener mListener, Class<?> class1) {
        MultipartBody.Builder builder =  new MultipartBody.Builder();
        Request.Builder buildRquest = new Request.Builder()
                .url(getAbsoluteUrl(url))
                .post(myParams.getRequestBodyWithFile());
        AddHeaderToBuilder(buildRquest,myParams,false);
        Request request = buildRquest.build();
        try {
            Response response = getAsyncHttpClient().newCall(request).execute();
            MyHttpResposeHandlerForSync myhandler = new MyHttpResposeHandlerForSync(mListener,0,class1);
            myhandler.onResponse(null,response);
        } catch (IOException e) {
            e.printStackTrace();
            mListener.onFailure(0,null);
        }

    }

    /**
     * 没有断点续传功能的get请求下载
     * @param downUrl 下载网络地址
     */
    public static Call download( String downUrl, String destFileParent,String saveFileName, MyHttpListener listener) {
        Request request = new Request.Builder()
                .url(downUrl)
                .get()
                .build();
       Call mCall = getAsyncHttpClient().newCall(request);//构建了一个完整的http请求
        mCall.enqueue(new MyHttpDownloadCallBack(listener,destFileParent,saveFileName));
        return  mCall;
    }

    public static String getAbsoluteUrl(String relativeUrl) {
        if (relativeUrl.startsWith("http")) {
//            LogUtil.i(tag,relativeUrl);
            return relativeUrl;
        } else {
//            LogUtil.i(tag, MyUtils.getServiceAPI()+relativeUrl);
            String urlReal = MyUtils.getServiceAPI()+relativeUrl;
//            if(relativeUrl.contains(Constants.URL_VIDEO_GET_CATALOG) || relativeUrl.contains(Constants.URL_VIDEO_GET_PLAY_URL)){
//                String urlServere = MyUtils.getServiceAPI();
//                urlServere = urlServere.substring(0,urlServere.indexOf(":")+1)+"5666";
//                urlReal = urlServere +relativeUrl;
//            }
            if(urlReal.startsWith("http://192.") && urlReal.contains("/serv/")){
                urlReal = urlReal.replaceFirst("/serv/","/");
            }
            LogUtil.i(tag,urlReal);
            return urlReal;
//            return relativeUrl;
        }
    }

    public static void AddHeaderToBuilder(Request.Builder build, boolean isGet){
//        build.header("Content-Type", "application/json");
//        build.header("XF-API-clienttype", "android");
//        build.header("XF-API-clientversion", SystemParamsUtils.getAppVersonName(BasisApp.getInstance()));
//        build.header("XF-API-osversion", SystemParamsUtils.getSystemReleaseVersion());
//        if(myParams != null && myParams.getUrlParams().keySet().contains(MyParams.PARAMS_LOG)){
//            build.header(MyParams.PARAMS_LOG, myParams.getUrlParams().get(MyParams.PARAMS_LOG));
//        }
        build.header("Accept", "*/*");
        if(LoginBean.isLogin()){
            build.header("Authorization", LoginBean.getInstance().getToken());
        }
    }

    public static void AddHeaderToBuilder(Request.Builder build, MyParams myParams, boolean isGet){
//        build.header("Content-Type", "application/json");
//        build.header("XF-API-clienttype", "android");
//        build.header("XF-API-clientversion", SystemParamsUtils.getAppVersonName(BasisApp.getInstance()));
//        build.header("XF-API-osversion", SystemParamsUtils.getSystemReleaseVersion());
//        if(myParams != null && myParams.getUrlParams().keySet().contains(MyParams.PARAMS_LOG)){
//            build.header(MyParams.PARAMS_LOG, myParams.getUrlParams().get(MyParams.PARAMS_LOG));
//        }
        build.header("Accept", "*/*");
        if(LoginBean.isLogin()){
            build.header("Authorization", LoginBean.getInstance().getToken());
        }
    }

    public static void AddHeaderToBuilder(Request.Builder build){
//        build.header("Content-Type", "application/json");
//        build.header("XF-API-clienttype", "android");
//        build.header("XF-API-clientversion", SystemParamsUtils.getAppVersonName(BasisApp.getInstance()));
//        build.header("XF-API-osversion", SystemParamsUtils.getSystemReleaseVersion());
//        if(myParams != null && myParams.getUrlParams().keySet().contains(MyParams.PARAMS_LOG)){
//            build.header(MyParams.PARAMS_LOG, myParams.getUrlParams().get(MyParams.PARAMS_LOG));
//        }
        build.header("Accept", "*/*");
        if(LoginBean.isLogin()){
            build.header("Authorization", LoginBean.getInstance().getToken());
        }
    }


    public static Map<String, String > getWebViewHeader(){
        long time = new Date().getTime()/1000;
        Map<String, String > map = new HashMap<>();
//        map.put("APP-ID", HEADER_HTTP_SourceID);
//        map.put("APP-AUTHTIME", time + "");
//        map.put("APP-VERSION", SystemParamsUtils.getAPPVersonCode(BasisApp.mContext)+"");
//        map.put("APP-TYPE",  "android");
//        map.put("APP-IMEI",  SystemParamsUtils.getIMEI());
//        map.put("APP-DEVICE",SystemParamsUtils.getPhoneModel() + "");
//        map.put("APP-TOKEN", LoginBean.getUserToken());
        return map;
    }

//    private static final String HEADER_HTTP_SourceID = "156508686904";//appid测试用
//    private static final String HEADER_HTTP_AuthKey = "hpWexNVW1LEKGrBv";
//
//    private static void AddHeaderToBuilder(Request.Builder build, MyParams myParams, boolean isGet){
//        build.addHeader("Content-Type", "application/json");
//        build.addHeader("Authorization", "");
//        long time = new Date().getTime()/1000;
//        build.addHeader("APP-ID", HEADER_HTTP_SourceID);
//        build.addHeader("APP-AUTHTIME", time + "");
//        build.addHeader("APP-VERSION", SystemParamsUtils.getAPPVersonCode(BasisApp.mContext)+"");
//        build.addHeader("APP-TYPE",  "android");
//        build.addHeader("APP-IMEI",  SystemParamsUtils.getIMEI());
//        build.addHeader("APP-DEVICE",
//                SystemParamsUtils.getPhoneModel() + "");
////        if(LoginBean.isLogin()){
////            client.addHeader("APP-TOKEN", LoginBean.getUserToken());
////        }
//        build.addHeader("APP-TOKEN", LoginBean.getUserToken());
//        ArrayList<String> listP = new ArrayList<>();
//        listP.add("header_app_id="+HEADER_HTTP_SourceID);
////        listP.add("app_key="+HEADER_HTTP_AuthKey);
//        listP.add("header_app_token="+LoginBean.getUserToken());
//        listP.add("header_app_authtime="+time+"");
//        if(isGet){
//            if(myParams !=null){
//                for(String key:myParams.getUrlParams().keySet()){
//                    listP.add(key+"="+myParams.getUrlParams().get(key));
//                }
//            }
//        }
//
//        build.addHeader("APP-SIGN",getSecretStr(listP));
//    }
//
//    private static  String getSecretStr(ArrayList<String>  list) {
//        String result = "";
//        Collections.sort(list);
//        StringBuilder builder = new StringBuilder();
//        for(String data:list){
////            LogUtil.i(""+data);
//            builder.append(data).append("&");
//        }
//        builder.append("appkey="+HEADER_HTTP_AuthKey);
////        LogUtil.i("字符串"+builder.toString());
//        result = MD5.getMD5ofStrLowercase(builder.toString()).substring(0,32);
//
////        if(result.length()> 48){
////            result = result.substring(0,48).toUpperCase();
////        }
////            LogUtil.i("签名值"+result);
//        return result;
//    }

}


